import Router from '@koa/router'
import { z } from 'zod'
import { prisma } from '../../app'
import { createError } from '../../middleware/errorHandler'
import { generateToken } from '../../middleware/auth'

const router = new Router()

// 验证 schema
const registerSchema = z.object({
  email: z.string().email('Invalid email format'),
  username: z.string().min(3, 'Username must be at least 3 characters').max(50, 'Username must be at most 50 characters'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
  nickname: z.string().optional()
})

const loginSchema = z.object({
  email: z.string().email('Invalid email format').optional(),
  username: z.string().optional(),
  password: z.string().min(1, 'Password is required')
}).refine(data => data.email || data.username, {
  message: 'Either email or username is required'
})

// 用户注册
router.post('/register', async (ctx) => {
  try {
    const { email, username, password, nickname } = registerSchema.parse(ctx.request.body)

    // 检查用户是否已存在
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          { email },
          { username }
        ]
      }
    })

    if (existingUser) {
      if (existingUser.email === email) {
        throw createError.conflict('Email already exists')
      }
      if (existingUser.username === username) {
        throw createError.conflict('Username already exists')
      }
    }

    // 创建用户
    const user = await prisma.user.create({
      data: {
        email,
        username,
        password,
        nickname: nickname || username
      },
      select: {
        id: true,
        email: true,
        username: true,
        nickname: true,
        createdAt: true
      }
    })

    // 生成 token
    const token = generateToken({
      userId: user.id,
      email: user.email,
      username: user.username
    })

    ctx.body = {
      success: true,
      message: 'User registered successfully',
      data: {
        user,
        token
      }
    }
  } catch (error) {
    throw error
  }
})

// 用户登录
router.post('/login', async (ctx) => {
  try {
    const { email, username, password } = loginSchema.parse(ctx.request.body)

    // 查找用户
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          email ? { email } : {},
          username ? { username } : {}
        ].filter(condition => Object.keys(condition).length > 0)
      }
    })

    if (!user) {
      throw createError.unauthorized('Invalid credentials')
    }

    // 生成 token
    const token = generateToken({
      userId: user.id,
      email: user.email,
      username: user.username
    })

    ctx.body = {
      success: true,
      message: 'Login successful',
      data: {
        user: {
          id: user.id,
          email: user.email,
          username: user.username,
          nickname: user.nickname,
          avatar: user.avatar
        },
        token
      }
    }
  } catch (error) {
    throw error
  }
})

// 刷新 token
router.post('/refresh', async (ctx) => {
  try {
    if (!ctx.user) {
      throw createError.unauthorized('User not authenticated')
    }

    // 查找用户以确保用户仍然存在
    const user = await prisma.user.findUnique({
      where: { id: ctx.user.userId },
      select: {
        id: true,
        email: true,
        username: true
      }
    })

    if (!user) {
      throw createError.unauthorized('User not found')
    }

    // 生成新的 token
    const token = generateToken({
      userId: user.id,
      email: user.email,
      username: user.username
    })

    ctx.body = {
      success: true,
      message: 'Token refreshed successfully',
      data: {
        token
      }
    }
  } catch (error) {
    throw error
  }
})

export default router
